package util;

import lombok.Builder;
import lombok.Data;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;

import javax.validation.*;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 参数校验工具类
 */
public class ValidationUtils {
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false)
            .buildValidatorFactory().getValidator();

    public static <T> void validate(T obj) {
        Set<ConstraintViolation<T>> constrainViolations = validator.validate(obj);
        if (constrainViolations.size() > 0) {
            ConstraintViolation<T> next = constrainViolations.iterator().next();
            System.out.println(next.getPropertyPath() +" "+ next.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        A a = A.builder()
                .age(120L)
                .name("aaaa")
                .pat("")
                .myRegex(2)
                .build();

        validate(a);
    }

    @Data
    @Builder
    private static class A {
        /**
         * 自定义正则
         */
        @NotNull
        @ValidInteger(regex = "1|2",message = "只允许1|2")
        private Integer myRegex;

        /**
         * 字符串
         */
        @DecimalMax(value = "3.9")
        private String name;

        /**
         * 数字
         */
        @NotNull
        @Range(min = 10,max = 120)
        private Long age;


        /**
         * 正则
         */
        @javax.validation.constraints.Pattern(regexp = "^(\\s&&[^\\f\\n\\r\\t\\v])*|1|2",message = "格式不正确")
        private String pat;

    }


    @Target({ElementType.FIELD, ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = MoneyValidator.class)
    public @interface ValidInteger {
        String message() default "格式错误";

        Class<?>[] groups() default {};

        Class<? extends Payload>[] payload() default {};

        String regex();//可自定义正则
    }

    public static class MoneyValidator implements ConstraintValidator<ValidInteger, Integer> {
        private Pattern compile;

        public void initialize(ValidInteger validInteger) {
            String regex = validInteger.regex();
            compile = Pattern.compile(regex);
        }

        public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
            if (value == null)
                return true;
            return compile.matcher(value.toString()).matches();
        }
    }


}
